package com.tuniu.agents.tools.train.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

import static com.tuniu.agents.tools.train.constants.TrainCommonConstants.DATETIME_PATTERN;
import static com.tuniu.agents.tools.train.constants.TrainCommonConstants.SUBTIME_PATTERN;

@Slf4j
public class TrainCommonUtil {


    /**
     * Process price: if decimal part is 0, return integer part
     * @param price
     * @return
     */
    public static String formatPrice(String price) {
        if (price == null || price.isEmpty()) {
            return price;
        }

        try {
            BigDecimal decimal = new BigDecimal(price);
            // If decimal part is zero, return integer part
            return decimal.stripTrailingZeros().toPlainString();
        } catch (NumberFormatException e) {
            log.error("TrainCommonUtil format price error price:{}", price,e);
            // If parsing fails, return original value
            return price;
        }
    }

    /**
     * extract year-month-day from string
     */
    public static String extractDate(String dateTimeStr) {
        if (StringUtils.isEmpty(dateTimeStr)) {
            return null;
        }
        try {
            // LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(DATETIME_PATTERN));
            return dateTime.format(DateTimeFormatter.ISO_DATE); // Output format: 2025-03-17

            // Or use custom output format
            // return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } catch (DateTimeParseException e) {
            log.warn("train Failed to parse date time string: {}", dateTimeStr, e);
            return null;
        }
    }

    /**
     * extract hour:minute from string
     */
    public static String extractSubTime(String dateTimeStr) {
        if (StringUtils.isEmpty(dateTimeStr)) {
            return null;
        }
        try {
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(DATETIME_PATTERN));
             return dateTime.format(DateTimeFormatter.ofPattern(SUBTIME_PATTERN)); // 输出格式：14:30
        } catch (DateTimeParseException e) {
            log.warn("train Failed to parse date time string: {}", dateTimeStr, e);
            return null;
        }
    }

    /**
     * Generate unique train ticket identifier
     *
     * A single location may have multiple train stations, resulting in multiple train tickets
     * for the same train number passing through different stations at that location
     * Therefore, trainNum alone cannot uniquely identify a train ticket
     * Format: train number + departure and arrival time digits (example: G123408301425)
     */
    public static String generateNumericTrainId(String trainNum, String departureTime, String arrivalTime) {
        return new StringBuilder(16)
                .append(trainNum.replaceAll("[^0-9]", ""))
                .append((extractSubTime(departureTime) + extractSubTime(arrivalTime)).replace(":", ""))
                .toString();
    }

}
